package alp.starcode.edms.dict.service;

import alp.starcode.common.base.exception.DataNotExistException;
import alp.starcode.common.base.exception.OperateException;
import alp.starcode.common.mybatis.page.Pagination;
import alp.starcode.edms.db.dao.DictTypeDao;
import alp.starcode.edms.db.entity.DictType;
import alp.starcode.edms.dict.model.dto.DictTypeDto;
import alp.starcode.edms.dict.model.vo.DictTypeVo;
import alp.starcode.edms.framework.base.BaseService;
import alp.starcode.edms.framework.handler.CurrentUserComponent;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * 字典类型管理 业务层
 *
 * @author Clxini
 * @since 2025-01-17
 */
@Slf4j
@Service
public class DictTypeService extends BaseService {

    @Resource
    private DictTypeDao dictTypeDao;

    @Resource
    private CurrentUserComponent currentUserComponent;

    /**
     * 分页查询字典类型列表
     *
     * @param dictTypeName 字典类型名称
     * @param dictTypeCode 字典类型编码
     * @param pagination   分页对象
     * @return 字典类型列表
     */
    public Pagination<DictTypeVo> pageDictType(String dictTypeName, String dictTypeCode, Pagination<DictTypeVo> pagination) {
        // 构建查询条件
        MPJLambdaWrapper<DictType> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(DictType::getIsDeleted, false);
        queryWrapper.like(StringUtils.hasText(dictTypeName), DictType::getDictTypeName, dictTypeName);
        queryWrapper.like(StringUtils.hasText(dictTypeCode), DictType::getDictTypeCode, dictTypeCode);
        // 默认排序方式
        queryWrapper.orderByDesc(DictType::getCreateTime);
        // 查询结果
        return dictTypeDao.selectJoinListPage(pagination, DictTypeVo.class, queryWrapper);
    }

    /**
     * 根据ID查询字典类型详情
     *
     * @param dictTypeId 字典类型ID
     * @return 字典类型详情
     */
    public DictTypeVo getDictTypeById(String dictTypeId) {
        // 构建查询条件
        MPJLambdaWrapper<DictType> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(DictType::getDictTypeId, dictTypeId);
        queryWrapper.eq(DictType::getIsDeleted, false);
        // 查询结果
        return dictTypeDao.selectJoinOne(DictTypeVo.class, queryWrapper);
    }

    /**
     * 根据编码查询字典类型详情
     *
     * @param dictTypeCode 字典类型编码
     * @return 字典类型详情
     */
    public DictTypeVo getDictTypeByCode(String dictTypeCode) {
        // 构建查询条件
        MPJLambdaWrapper<DictType> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(DictType::getDictTypeCode, dictTypeCode);
        queryWrapper.eq(DictType::getIsDeleted, false);
        // 查询结果
        return dictTypeDao.selectJoinOne(DictTypeVo.class, queryWrapper);
    }

    /**
     * 新增字典类型
     *
     * @param dictTypeDto 字典类型信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void addDictType(DictTypeDto dictTypeDto) {
        // 检查编码是否已存在
        if (checkDictTypeCodeExists(dictTypeDto.getDictTypeCode(), null)) {
            throw new OperateException("字典类型编码已存在：[%s]", dictTypeDto.getDictTypeCode());
        }

        // 构建实体对象
        DictType dictType = new DictType();
        BeanUtils.copyProperties(dictTypeDto, dictType);
        dictType.setDictTypeId(UUID.randomUUID().toString());
        dictType.setIsDeleted(false);
        dictType.setCreateUserId(currentUserComponent.getCurrentUserId());
        dictType.setCreateUserName(currentUserComponent.getCurrentUserName());
        dictType.setCreateTime(System.currentTimeMillis());
        dictType.setUpdateUserId(currentUserComponent.getCurrentUserId());
        dictType.setUpdateUserName(currentUserComponent.getCurrentUserName());
        dictType.setUpdateTime(System.currentTimeMillis());

        // 保存数据
        boolean result = dictTypeDao.save(dictType);
        if (!result) {
            throw new OperateException("新增字典类型失败");
        }
    }

    /**
     * 修改字典类型
     *
     * @param dictTypeDto 字典类型信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateDictType(DictTypeDto dictTypeDto) {
        // 检查数据是否存在
        DictType existDictType = dictTypeDao.getById(dictTypeDto.getDictTypeId());
        if (existDictType == null || existDictType.getIsDeleted()) {
            throw new DataNotExistException("字典类型不存在，无法修改：[%s]", dictTypeDto.getDictTypeId());
        }

        // 检查编码是否已存在（排除当前记录）
        if (checkDictTypeCodeExists(dictTypeDto.getDictTypeCode(), dictTypeDto.getDictTypeId())) {
            throw new OperateException("字典类型编码已存在：[%s]", dictTypeDto.getDictTypeCode());
        }

        // 构建实体对象
        DictType dictType = new DictType();
        BeanUtils.copyProperties(dictTypeDto, dictType);
        dictType.setUpdateUserId(currentUserComponent.getCurrentUserId());
        dictType.setUpdateUserName(currentUserComponent.getCurrentUserName());
        dictType.setUpdateTime(System.currentTimeMillis());

        // 更新数据
        boolean result = dictTypeDao.updateById(dictType);
        if (!result) {
            throw new OperateException("修改字典类型失败");
        }
    }

    /**
     * 删除字典类型
     *
     * @param dictTypeId 字典类型ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteDictType(String dictTypeId) {
        // 检查数据是否存在
        DictType existDictType = dictTypeDao.getById(dictTypeId);
        if (existDictType == null || existDictType.getIsDeleted()) {
            throw new DataNotExistException("字典类型不存在，无法删除：[%s]", dictTypeId);
        }

        // 逻辑删除字典类型
        DictType dictType = new DictType();
        dictType.setDictTypeId(dictTypeId);
        dictType.setIsDeleted(true);
        dictType.setUpdateUserId(currentUserComponent.getCurrentUserId());
        dictType.setUpdateUserName(currentUserComponent.getCurrentUserName());
        dictType.setUpdateTime(System.currentTimeMillis());

        boolean result = dictTypeDao.updateById(dictType);
        if (!result) {
            throw new OperateException("删除字典类型失败");
        }
    }

    /**
     * 获取所有字典类型列表（不分页）
     *
     * @return 字典类型列表
     */
    public List<DictTypeVo> getAllDictTypeList() {
        // 构建查询条件
        MPJLambdaWrapper<DictType> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(DictType::getIsDeleted, false);
        queryWrapper.orderByAsc(DictType::getDictTypeName);
        // 查询结果
        return dictTypeDao.selectJoinList(DictTypeVo.class, queryWrapper);
    }

    /**
     * 检查字典类型编码是否存在
     *
     * @param dictTypeCode 字典类型编码
     * @param excludeId    排除的ID
     * @return 是否存在
     */
    public boolean checkDictTypeCodeExists(String dictTypeCode, String excludeId) {
        LambdaQueryWrapper<DictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DictType::getDictTypeCode, dictTypeCode);
        queryWrapper.eq(DictType::getIsDeleted, false);
        if (StringUtils.hasText(excludeId)) {
            queryWrapper.ne(DictType::getDictTypeId, excludeId);
        }
        return dictTypeDao.count(queryWrapper) > 0;
    }
} 